//
//  ThreadController.swift
//  HHSwift
//
//  Created by 华宏 on 2019/1/25.
//  Copyright © 2019年 huahong. All rights reserved.
//

import UIKit

class ThreadController: BaseViewController {

    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       
                
        //        gcdDemo()
                
        //        gcdGroup()
                
        //        dispatch_group()
                
//        barrier()
        
        asyncAfter()
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "GCD"
  
        //串行队列
        let _ = DispatchQueue(label: "serial", attributes: .init(rawValue: 0))
        
        //并发队列
        let _ = DispatchQueue(label: "concurrent",attributes: .concurrent)
        
        //主队列
        let _ = DispatchQueue.main
        
        //全局队列
        let _ = DispatchQueue.global()
        
    
        
        
    }
   

//MARK: - GCD
    
    func asyncAfter() {
      
        let workItem = DispatchWorkItem.init {
           print("延迟执行1")
        }
        
        switch workItem.wait(timeout: .now()+2) {
        case .success:
           print("success")
        default:
           print("timeout")
        }
        
        
        workItem.notify(queue: DispatchQueue.main) {
           print("completed")
        }
        
        DispatchQueue.global().asyncAfter(deadline: .now()+1, execute: workItem)
        
//        workItem.cancel()
        
        
        DispatchQueue.global().asyncAfter(deadline: .now()+3) {
             print("延迟执行2")
        }
        
        
        //执行
        DispatchWorkItem{
            print("DispatchWorkItem")
        }.perform()
        
       
        
        
        
    }
    
   private func gcdDemo()
   {
        DispatchQueue.global().async {
           
            print("异步执行:\(Thread.current)")
            
            DispatchQueue.main.async {
                print("主线程:\(Thread.current)")
            }

        }
    
    }
    
    //并行执行，notify最后执行
    func gcdGroup() {
        
        let group = DispatchGroup()
        
        group.enter()
        DispatchQueue.global().async {
            Thread.sleep(forTimeInterval: 2)
            print("异步执行A:\(Thread.current)")
            group.leave()
        }
        
        group.enter()
        DispatchQueue.global().async {
            print("异步执行B:\(Thread.current)")
            group.leave()
        }
        
        group.notify(queue: DispatchQueue.main) {
            print("OK:\(Thread.current)")
        }
        
    }
    
    
    func dispatch_group() {
        let group = DispatchGroup()
        let globalQueue = DispatchQueue.global()

        globalQueue.async(group: group, execute: DispatchWorkItem.init(block: {
            print("1111111111111")
        }))
        
        globalQueue.async(group: group, execute: DispatchWorkItem.init(block: {
            
           sleep(2)
           print("222222222222")
            
        }))
        
        globalQueue.async(group: group, execute: DispatchWorkItem.init(block: {
           print("3333333333333")
        }))
        
        group.notify(queue: DispatchQueue.main) {
           print("Over:\(Thread.current)")
        }
        
        let timeoutResult:DispatchTimeoutResult = group.wait(timeout: .distantFuture)
        switch timeoutResult {
        case .success:
            print("success")
        case .timedOut:
            print("timeout")
            
        }
        
        
    }
   
    
    func barrier() {
        
       //只能用并发队列(全局队列也不可以)，要放在同一个队列
        
        let queue = DispatchQueue(label: "concurrent",attributes: .concurrent)
        
        queue.async {
            print(111111111111)
        }
        
        queue.async {
            print(22222222222222)
        }
        
        queue.async {
            sleep(2)
            print(333333333333333)
        }
        
        queue.async {
            print(44444444444444)
        }
        
        
        queue.async(flags: .barrier) {
             print("this is barrier")
        }
        
        queue.async {
            print(555555555555)
        }
        
        queue.async {
            print(666666666666)
        }
        
        queue.async {
            print(77777777777)
        }
        
        queue.async {
            print(88888888888888)
        }
       
    }
    

//MARK: - Operation
    
    func Operation() {
        
        OperationQueue().addOperation {
            
            sleep(2)
            
            OperationQueue.main.addOperation {
                 //config UI
                print("currentThread:",OperationQueue.current ?? "")
            }
        }
        
        
        
        
        
    }
    
    
    
    func Operation1() {
         
        let queue = OperationQueue.init()
        
        queue.qualityOfService = .default
        queue.maxConcurrentOperationCount = 6
        
//        queue.cancelAllOperations()
//        queue.waitUntilAllOperationsAreFinished()
//        queue.addBarrierBlock {
//
//        }
        
        let op = BlockOperation {
           
            print("BlockOperation")
        }
        
        let op1 = BlockOperation {
           
            print("BlockOperation1")
        }
        
        //依赖
        op1.addDependency(op)
        
        op1.cancel()
        
        queue.addOperation(op)
        
        queue.addOperations([op,op1], waitUntilFinished: true)
           
       }
       
    
 //MARK: - Lock
    func lock()  {
        let lock = NSLock()
        lock.lock()
        lock.unlock()
        
        
        //互斥锁
        objc_sync_enter(self)
        
        objc_sync_exit(self)
        
    }
    
}
